import { Node, Vec2, v2, _decorator, Component, find, v3, Label, EventTouch, Camera, } from 'cc'
const { ccclass, property } = _decorator;
import { Building, DiamondConsume, EventOper } from '../entity/Buildings'
import { buildingType } from '../settings/const'
import { Space } from './Space'
import { Utils } from '../common/Utils'
import { VillageCamera } from './VillageCamera';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { BuildingBtnCheck, CheckResult } from './BuildingBtnCheck';
import { BuildingList } from './BuildingList';

import { UserInfo } from '../common/UserInfo';
import { VillageController } from './VillageController';
import { BuildingUpGrade } from './BuildingUpGrade';
import { BuildingLocalApi } from './BuildingLocalApi';
import { EventManager } from '../event/EventManager';
import { Wall } from './Wall';
import { BManager } from '../entity/BManager';
export enum SpaceBtnType {
     Build = 0,
     Remove = 1,
     UpGrade = 2,
     Develop = 3,
     Detail = 4,
     Cancel = 5,
     Speed = 6,
     Army = 7,
     Transport = 8,
     Train = 9,
     Expand = 10,
     Union = 11,
     Trea = 12,
     HeroYard = 13,
}

export const SpaceBtnConfig = {
     [buildingType.B00_NULL]: [SpaceBtnType.Build],
     [buildingType.B01_Wood]: [SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B02_Mud]: [SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B03_Iron]: [SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B04_Food]: [SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B05_Sawmill]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B06_Brickyard]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B07_Foundry]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B08_GrainMill]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B09_Bakery]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B10_Warehouse]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B11_Granary]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B12_Blacksmith]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Develop, SpaceBtnType.Detail],
     [buildingType.B13_Armoury]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Develop, SpaceBtnType.Detail],
     [buildingType.B14_Arena]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B15_MainBuilding]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B16_RallyPoint]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Army, SpaceBtnType.Detail],
     [buildingType.B17_Market]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Transport, SpaceBtnType.Detail],
     [buildingType.B18_Embassy]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Union, SpaceBtnType.Detail],
     [buildingType.B19_Barracks]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Train, SpaceBtnType.Detail],
     [buildingType.B20_Stable]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Train, SpaceBtnType.Detail],
     [buildingType.B21_Workshop]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Train, SpaceBtnType.Detail],
     [buildingType.B22_Academy]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Develop, SpaceBtnType.Detail],
     [buildingType.B23_Cranny]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B24_TownHall]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B25_Residence]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Expand, SpaceBtnType.Detail],
     [buildingType.B26_Palace]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Expand, SpaceBtnType.Detail],
     [buildingType.B27_Treasury]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Trea, SpaceBtnType.Detail],
     [buildingType.B28_TradeOffice]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B29_G_Barracks]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Train, SpaceBtnType.Detail],
     [buildingType.B30_G_Stable]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Train, SpaceBtnType.Detail],
     [buildingType.B31_H_Wall]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B32_X_Wall]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B33_M_Wall]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B34_Stonemason]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B35_Brewery]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B36_Trapper]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B37_HeroMasion]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade,SpaceBtnType.HeroYard, SpaceBtnType.Detail],
     [buildingType.B38_G_Warehouse]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B39_G_Granary]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
     [buildingType.B40_Wonder]: [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail],
}

@ccclass('SpaceBtn')
export class SpaceBtn extends Component {
     @property(Node)
     dot: Node

     @property(Node)
     public build: Node;
     @property(Node)
     public remove: Node;
     @property(Node)
     public upGrade: Node;
     @property(Node)
     public develop: Node;
     @property(Node)
     public detail: Node;
     @property(Node)
     public cancel: Node;
     @property(Node)
     public speed: Node;
     @property(Node)
     public army: Node;
     @property(Node)
     public transport: Node;
     @property(Node)
     public train: Node;
     @property(Node)
     public expand: Node;
     @property(Node)
     public union: Node;
     @property(Node)
     public trea: Node;
     @property(Node)
     public heroYard: Node;
     @property(Node)
     public title: Node
     @property(Label)
     public titleLabel: Label
     @property(Node)
     bg:Node

     /**所有操作按钮的列表 */
     public btnList: Node[] = []
     /**升级按钮是否可用 */
     private upGradeUse: boolean = false
     /**拆除按钮是否可用 */
     private removeUse: boolean = false
     /**加速按钮是否可用 */
     private speedUse: boolean = false
     private buildData: Building
     private space: Space

     radius: number = 150
     center: number = -90
     offset: number = 45

     static instance: SpaceBtn
     protected onLoad(): void {
          SpaceBtn.instance = this
     }



     protected start(): void {
          this.node.on(Node.EventType.TOUCH_END, this.onClose, this)

          this.build.on(Node.EventType.TOUCH_END, this.onBuild, this)
          this.detail.on(Node.EventType.TOUCH_END, this.onDetail, this)
          this.remove.on(Node.EventType.TOUCH_END, this.onRemove, this)
          this.upGrade.on(Node.EventType.TOUCH_END, this.onUpGrade, this)
          this.cancel.on(Node.EventType.TOUCH_END, this.onCancel, this)
          this.speed.on(Node.EventType.TOUCH_END, this.onSpeed, this)
          this.develop.on(Node.EventType.TOUCH_END, this.onDevelop, this)

          this.army.on(Node.EventType.TOUCH_END, this.onArmy, this)
          this.transport.on(Node.EventType.TOUCH_END, this.onTransport, this)
          this.train.on(Node.EventType.TOUCH_END, this.onTrain, this)
          this.expand.on(Node.EventType.TOUCH_END, this.onExpand, this)
          this.union.on(Node.EventType.TOUCH_END, this.onUnion, this)
          this.trea.on(Node.EventType.TOUCH_END, this.onTrea, this)
          this.heroYard.on(Node.EventType.TOUCH_END, this.onHeroYard, this)


        

          this.btnList = [
               this.build, this.remove, this.upGrade,
               this.develop, this.detail, this.cancel,
               this.speed, this.army, this.transport,
               this.train, this.expand, this.union,
               this.trea, this.heroYard
          ]



          this.hideAllBtn()

          this.showBtn()
     }




     setData(space: Space, eventTouch?: EventTouch) {
          this.buildData = space.buildData
          this.space = space
          let worldPos = this.space.node.worldPosition

          if (eventTouch) {
               let uicamera = find('Canvas/UICamera').getComponent(Camera)
               let worldPos = uicamera.screenToWorld(v3(eventTouch.getLocationX(), eventTouch.getLocationY(), 0))
               this.dot.position = uicamera.convertToUINode(worldPos, this.node)
          } else {
               this.dot.position = VillageCamera.instance.camera.convertToUINode(worldPos, this.node)
          }



          this.title.active = true
          if (this.buildData.id == 0) {
               this.titleLabel.string = this.buildData.name
          } else {
               this.titleLabel.string = `${this.buildData.name}${this.buildData.level}级,人口${this.buildData.people}`
          }
          Utils.showToPosition(this.title, v2(0, 150))

     }

     showBtn() {
          this.bg.active = true


          let btnList = this.btnList
          let building = this.buildData


          for (let item of btnList) {
               item.active = false
          }
          let config = SpaceBtnConfig[building.id]

          // 如果没有找到配置的情况
          if (!config) {
               config = [SpaceBtnType.Remove, SpaceBtnType.UpGrade, SpaceBtnType.Detail]
          }
          // 建筑院10级才会有拆除功能
          let bm = BManager.getBManageById(buildingType.B15_MainBuilding)
          if(bm.grade < 10){
               for (let i = config.length - 1; i >= 0; i--) {
                    if (config[i] == SpaceBtnType.Remove) {
                         config.splice(i, 1)
                    }
               }
          }
          
          // 如果是满级的情况
          if (building.level >= building.maxLevel) {
               for (let i = config.length - 1; i >= 0; i--) {
                    if (config[i] == SpaceBtnType.UpGrade) {
                         config.splice(i, 1)
                    }
               }
          }
          // 如果是正在建造或者拆除
          if (building.isBuilding || building.isRemoving) {
               config = [SpaceBtnType.Cancel, SpaceBtnType.Speed, SpaceBtnType.Detail]
          }

          // 如果是拆除，给加速按钮上添加一个元宝的图标
          if(building.isRemoving){
               btnList[SpaceBtnType.Speed].getChildByName('gold').active = true
          } else {
               btnList[SpaceBtnType.Speed].getChildByName('gold').active = false
          }

          // 如果时大小宫殿，就删除加速按钮
          if(building.id == buildingType.B25_Residence || building.id == buildingType.B26_Palace ){
               for (let i = config.length - 1; i >= 0; i--) {
                    if (config[i] == SpaceBtnType.Speed) {
                         config.splice(i, 1)
                    }
               }
          }
          


          let list: Node[] = []
          for (let item of config) {
               list.push(btnList[item])
          }
          let posList = this.getPosList(list.length)

          for (let i = 0; i < list.length; i++) {
               Utils.showToPosition(list[i], posList[i])
          }

     }


     getPosList(length: number): Vec2[] {
          let num = Math.floor(length / 2)
          let isEven = length % 2 == 0
          let list: Vec2[] = []

          if (isEven) {
               this.offset = 25

               for (let i = 0; i < num; i++) {
                    let index = i + 1

                    let addtion = 0
                    if(index > 1){
                         addtion = 15
                    }

                    list.unshift(this.degreeToPostion(this.center - this.offset * index - addtion))
                    list.push(this.degreeToPostion(this.center + this.offset * index + addtion))
               }
          } else {
               list.push(this.degreeToPostion(this.center))
               for (let i = 0; i < num; i++) {
                    let index = i + 1
                    list.unshift(this.degreeToPostion(this.center - this.offset * index))
                    list.push(this.degreeToPostion(this.center + this.offset * index))
               }
          }
          

          return list
     }

     degreeToPostion(d: number): Vec2 {

          let radian = Math.PI / 180 * d
          let x = Math.cos(radian) * this.radius
          let y = Math.sin(radian) * this.radius
          return v2(x, y)
     }


     hideAllBtn() {
          this.bg.active = false
          for (let item of this.btnList) {
               item.active = false
          }
     }

     onClose() {
          UIManager.instance.closeUI(PrefabEnum.SpaceBtn)
     }

     /**
     * 建造按钮点击的回调方法
     */
     async onBuild() {
          if (this.buildData.uid == 40) {
               EventManager.instance.emit(EventManager.EventType.BuildWall, this.buildData.uid)
          } else {
               let ui = await UIManager.instance.openUI(PrefabEnum.BuildingList)
               // ui.getComponent(BuildingList).createNewBuildings()
          }




          this.onClose()
     }

     /**
      * 详情按钮点击的回调方法
      */
     async onDetail() {
          let ui = await UIManager.instance.openUI(PrefabEnum.BuildingUpGrade)
          ui.getComponent(BuildingUpGrade).setData(this.buildData)

          this.onClose()
     }
     /**
    * 拆除按钮点击的回调方法
    */
     async onRemove() {
          let result = BuildingBtnCheck.chekcRemoveBtn(this.buildData)
          if (result != CheckResult.Pass) {
               return
          }

          if (this.buildData.uid == 40) {
               EventManager.instance.emit(EventManager.EventType.RemoveWall, 40)
          } else {
               this.space.onRemove()
          }

          this.onClose()

     }
     /**
     * 升级按钮点击的回调方法
     */
     onUpGrade() {
          if(!this.buildData.isEnoughConsumeForBuild){
               UIManager.instance.modal('提示', '粮食产量不足，请先升级农田', false)
               return
           }

          let result = BuildingBtnCheck.checkUpGrdeBtn(this.buildData)
          if (result != CheckResult.Pass) {
               return
          }

          if (this.buildData.uid == 40) {
               EventManager.instance.emit(EventManager.EventType.BuildWall, 40)
          } else {
               this.space.buildBuilding(this.buildData.gid)
          }


          this.onClose()
     }
     /**
     * 取消按钮点击的回调方法
     */
     async onCancel() {
          this.space.onCancel()

          this.onClose()

     }
     /**
     * 加速按钮点击的回调方法
     */
     async onSpeed() {
          // let result = BuildingBtnCheck.checkSpeedBtn(this.buildData)
          // if (result != CheckResult.Pass) {
          //      UIManager.instance.tip(result)
          //      return
          // }

          this.space.onSpeed()

          this.onClose()
     }
     /**
      * 研发按钮的回调
      */
     onDevelop() {
          UIManager.instance.openUI(PrefabEnum.DevelopIndex)
          this.onClose()
     }

     onArmy() {
          UIManager.instance.openUI(PrefabEnum.ArmyIndex)
          this.onClose()
     }
     onTransport() {
          if(UserInfo.instance.villageData.villageObjList.length == 1){
               UIManager.instance.modal('提示',`您只有一个村庄，没有可运往的村庄。`, false)
               return
           }
          UIManager.instance.openUI(PrefabEnum.Transport)
          this.onClose()
     }
     onTrain() {
          UIManager.instance.openUI(PrefabEnum.TrainIndex)
          this.onClose()
     }

     onExpand() {
          UIManager.instance.openUI(PrefabEnum.PalaceIndex)
          this.onClose()
     }

     onUnion() {
          UIManager.instance.openUI(PrefabEnum.AllyIndex)
          this.onClose()
     }

     onTrea() {
          UIManager.instance.openUI(PrefabEnum.Trea)
          this.onClose()
     }

     onHeroYard(){
          UIManager.instance.openUI(PrefabEnum.HeroYard)
          this.onClose()
     }


}